#include "Wifi_Ctrl.h"

/*静态全局变量*/
static int status = WL_IDLE_STATUS;//用来在WiFi事件回调函数里面与WiFi循环里面记录当前的WiFi状态
static bool sta_connect_flag = false;//用作记录当前是STA模式连接成功
static volatile uint8_t wifi_mode = 0;//用作判断当前是WiFi普通模式还是smartconfig模式
static uint8_t sta_disconnect_cnt = 0;//计数,计算有多少次进入到WiFi事件注册函数中的STA断开事件
static volatile bool wifi_reconnect_flag = false;//用来判断WiFi是否需要重连

/*全局变量*/
static Ticker Ticker_wifi_reconnect;//用来判断WiFi重启
extern volatile uint8_t machine_rest_flag;//控制机器启动


void wifi_reconnect(void)
{
    wifi_reconnect_flag = true;
}

/*全局函数*/
uint8_t Get_Wifi_Mode(void)
{
    return wifi_mode;
}

bool Get_Wifi_State(void)
{
   if(sta_connect_flag)
   {
       return true;
   }
   return false;
}


void WiFiEvent(WiFiEvent_t event)
{
    switch(event)
    {
    case SYSTEM_EVENT_WIFI_READY:/**< ESP32 WiFi ready */
    {
        Serial.println("WiFi ready");
        break;
    }          
         
    case SYSTEM_EVENT_AP_START:
    {
        Serial.println("AP Started");
        break;
    }

    case SYSTEM_EVENT_AP_STOP:
    {
        Serial.println("AP Stopped");
        break;
    }

    case SYSTEM_EVENT_STA_START:
    {
        Serial.println("STA Started");

        status = WL_IDLE_STATUS;
        break;
    }

    case SYSTEM_EVENT_STA_CONNECTED:
    {
        Serial.println("STA Connected");

        sta_connect_flag = true;
        status = WL_IDLE_STATUS;

        break;
    }

    case SYSTEM_EVENT_AP_STA_GOT_IP6:
    {
        Serial.print("STA IPv6: ");
        Serial.println(WiFi.localIPv6());

        break;
    }

    case SYSTEM_EVENT_STA_GOT_IP:
    {
        Serial.print("STA IPv4: ");
        Serial.println(WiFi.localIP());

        break;
    }

    case SYSTEM_EVENT_STA_DISCONNECTED:
    {
        Serial.println("STA Disconnected");

        //如果此时是smartconfig配网模式,不执行下面的内容
        if(Get_Wifi_Mode() != 0)
        {
            break;
        }

        //判断此时WiFi是否不是AP模式或不是APSTA模式
        if(WiFi.getMode() != WIFI_MODE_AP || WiFi.getMode() != WIFI_MODE_APSTA)
        {
            status = WL_IDLE_STATUS;

            sta_disconnect_cnt++;
            if(sta_disconnect_cnt > 5)
            {
                // Serial.println("WiFi_MODE_NULL");

                // WiFi.mode(WIFI_MODE_NULL);//WiFi设置为断开

                return ;
            }
        }

        sta_connect_flag = false;

        //wifi_reconnect_flag = true;

        break;
    }

    case SYSTEM_EVENT_STA_STOP:
    {
        Serial.println("STA Stopped");

        break;
    }

    default:
    {
        Serial.printf("SYSTEM_EVENT %d\r\n", event);
        break;
    }
    }
}

//WiFi初始化函数
void WiFi_Setup(void)
{
    WiFi.onEvent(WiFiEvent);//注册WiFi事件回调函数


    WiFi.mode(WIFI_MODE_STA);//STA模式

    WiFi.begin("ALIENTEK","00000000");

    //每5s执行一次wifi_reconnect函数，反复执行
    Ticker_wifi_reconnect.attach(5,wifi_reconnect);
}

void WiFiMode_Set(bool flag)
{
    if(flag)//退出smartconfig模式
    {
        WiFi.stopSmartConfig();
        status = WL_IDLE_STATUS;
        WiFi.mode(WIFI_MODE_STA);

        WiFi.begin();

        Serial.println("stop smartconfig");

        Serial.printf("Wifi_Ctrl %d:%d\r\n",__LINE__,esp_get_free_heap_size());

        wifi_mode = 0;

    }
    else//进入smartconfig模式
    {
        sta_connect_flag = false;

        Disconnect_To_Aliyun();//断开阿里云物联网平台的连接

        WiFi.mode(WIFI_MODE_STA);
        WiFi.beginSmartConfig();

        Serial.println("begin smartconfig");

        Serial.printf("Wifi_Ctrl %d:ESP32 HEAP1:%d\r\n",__LINE__,esp_get_free_heap_size());

        wifi_mode = 1;
    }
}

void WiFi_Loop(void)
{
    static int wifi_reconnect_idx = 0;

    int status_tmp = WL_IDLE_STATUS;

    switch(wifi_mode)
    {
        case 0://一般模式
        {
            status_tmp = WiFi.status();//在循环中得到的WiFi状态

            if(status == WL_IDLE_STATUS)
            {
                if(status_tmp == WL_CONNECTED)//连上互联网
                {
                    status = WL_CONNECTED;

                    Serial.print("SSID: ");
                    Serial.println(WiFi.SSID());

                    // IPAddress ip =;
                    // Serial.print("IP Address:");
                    // Serial.println(ip);

                    Serial.printf("Wifi_Ctrl.cpp %d,ESP32 HEAP1:%d\r\n",__LINE__,esp_get_free_heap_size());

                    Connect_To_Aliyun();

                    Update_Id_Ssid_Macaddress_To_Aliyun(WiFi.localIP(),WiFi.SSID(),WiFi.macAddress());

                    sta_connect_flag = true;
                }
                else if(status_tmp == WL_DISCONNECTED)
                {
                    Disconnect_To_Aliyun();//断开与阿里云的连接

                    sta_connect_flag = false;

                    if((machine_rest_flag != MACHINE_CLOSE) && (wifi_reconnect_flag == true))//STA重连
                    {
                        wifi_reconnect_flag = false;
                        Serial.printf("\r\nWL_DISCONNECTED:WiFi reconnect......%d\r\n,Wifi_Ctrl %d,ESP32 HEAP1:%d\r\n",wifi_reconnect_idx,__LINE__,esp_get_free_heap_size());

                        wifi_reconnect_idx++;
                        WiFi.reconnect();
                    }
                }
                else if(status_tmp == WL_NO_SSID_AVAIL)
                {

                }
                else if(status_tmp == WL_IDLE_STATUS)
                {

                }
                else
                {
                    if(wifi_reconnect_flag == true)
                    {
                        wifi_reconnect_flag = false;
                        Serial.printf("\r\nelse:WiFi reconnect.....%d\r\n,Wifi_Ctrl.cpp %d,ESP32 HEAP:%d\r\n",wifi_reconnect_idx,__LINE__,esp_get_free_heap_size());
                        
                        wifi_reconnect_idx++;
                        WiFi.reconnect();
                    }

                    return ;
                }
            }
            else if(status == WL_CONNECTED)
            {
                if(status_tmp != WL_CONNECTED)
                {
                    Disconnect_To_Aliyun();

                    Serial.printf("WiFi_Loop %d:%d\r\n", __LINE__, status_tmp);
                    status = WL_IDLE_STATUS;

                    //wifi_reconnect_flag = true;
                    break;
                }
            }
            break;
        }

        case 1:
        {
            if(WiFi.smartConfigDone())
            {
                Serial.println("smartconfig success");

                wifi_mode = 0;
            }
            break;
        }

        default:
        {
            break;
        }
    }
}